<?php

namespace App\Http\Controllers\Index;

use App\Notifications\FindPassword;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Notification;
class PasswordController extends Controller
{
    //加载找回密码功能填写邮箱地址模板方法
    public function writeEmail(){
        //加载模板
        return view('index.password.email');
    }

    public function send(Request $request){
        //获取post数据
        //判断用户需要找回密码的时候填写的邮箱是否是user表中的邮箱
        $user=User::where('email','=',$request->input('email'))->first();
        if ($user){
            //使用通知类给用户发邮件
            Notification::send($user,new FindPassword($user['email']));
            //发送完邮件,展示一个模板,提示一个邮件发送成功的提示
            session()->flash('success','邮件已发送至您的邮箱，请去查收');
            return view('index.password.show');
        }else{
            //设置闪存
            session()->flash('danger','该邮箱地址尚未注册');
            return redirect()->route('writeEmail');
        }
    }

    public function resetPassword($email){
        $user=User::where('email','=',$email)->first();
        //加载重置密码模板
        return view('index.password.resetPassword',compact('user'));
    }

    public function update(Request $request){
        //获取post数据
        $post=$request->all();
        $this->validate($request,['password'=>'required|min:6|max:20|confirmed']);
        //找到对应的用户数据
        $user=User::where('email','=',$post['email'])->first();
        $user->password=bcrypt($post['password']);
        $user->save();
        //设置闪存并跳转
        session()->flash('success','密码重置成功，请重新登录');
        return redirect()->route('login');
    }

}
